cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : STL Containers : vector : operator[]
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
STL Containers
bitset
deque
list
map
multimap
multiset
priority_queue
queue
set
stack
vector
vector
comparison operators
vector::vector
vector::~vector
member functions:
· vector::assign
· vector::at
· vector::back
· vector::begin
· vector::capacity
· vector::clear
· vector::empty
· vector::end
· vector::erase
· vector::front
· vector::get_allocator
· vector::insert
· vector::max_size
· vector::operator=
· vector::operator[]
· vector::pop_back
· vector::push_back
· vector::rbegin
· vector::rend
· vector::reserve
· vector::resize
· vector::size
· vector::swap

-

vector::operator[] public member function
      reference operator[] ( size_type n );
const_reference operator[] ( size_type n ) const;

Access element

Returns a reference to the element at position n in the vector container.

A similar member function, vector::at, has the same behavior as this operator function, except that vector::at signals if the requested position is out of range by throwing an exception.

Parameters

n
Position of an element in the vector.
Notice that the first element has a position of 0, not 1.
Member type size_type is an unsigned integral type.

Return value

The element at the specified position in the vector.

Member types reference and const_reference are the reference types to the elements of the vector container (generally defined as T& and const T& respectivelly in most storage allocation models).

Example

// vector::operator[]
#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> myvector (10);   // 10 zero-initialized elements
  unsigned int i;

  vector<int>::size_type sz = myvector.size();

  // assign some values:
  for (i=0; i<sz; i++) myvector[i]=i;

  // reverse vector using operator[]:
  for (i=0; i<sz/2; i++)
  {
    int temp;
    temp = myvector[sz-1-i];
    myvector[sz-1-i]=myvector[i];
    myvector[i]=temp;
  }

  cout << "myvector contains:";
  for (i=0; i<sz; i++)
    cout << " " << myvector[i];

  cout << endl;

  return 0;
}

Output:

myvector contains: 9 8 7 6 5 4 3 2 1 0

Complexity

Constant.

See also

vector::at Access element (public member function)
vector::front Access first element (public member function)
vector::back Access last element (public member function)

© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us